
import json

from django.contrib import messages
import re as rerule
import requests
from django.http import HttpResponseRedirect, request
from django.shortcuts import render,redirect,get_object_or_404,HttpResponse
from django.urls import reverse
from django.contrib import auth
import datetime
import time
from django.views.decorators.clickjacking import xframe_options_exempt
from .forms import LoginForm, ProjectcreateForm, ProjectupdateForm, UsercreateForm, UserupdateForm, \
    GroupupdateForm, GroupcreateForm, RolecreatForm, RoleUpdateForm, ServercreatForm, ShotcreatForm, ImagecreatForm, \
    FilecreatForm


# 获取domain范围token
def get_domain_token(username,password):
    data = {
        "auth": {
         "identity": {
            "methods": [
                "password"
            ],
            "password": {
                "user": {
                    "name": username,
                    "domain": {
                        "name": "default"
                    },
                    "password": password
                }
            }
        },
        "scope": {
            "domain": {
                    "name": "default",
                }
        }
    }
}
    url = "http://192.168.119.128:5000/v3/auth/tokens"
    result = requests.post(url, data=json.dumps(data))
    # 返回的token在 response header 里面
    return result

# 显示domain的详细信息
def domain_info(domain_token,domain_id):
    url = "http://192.168.119.128:5000/v3/domains/%s"%(domain_id)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result

# 获取project范围token
def get_project_token(domain_token):
    data = {
        "auth": {
            "identity": {
                "methods": [
                    "token"
                ],
                "token": {
                    "id": domain_token
                }
            },
            "scope": {
                "project": {
                    "domain": {
                        "name": "default",
                    },
                    "name": "admin"
                }
            }
        }
    }
    url = "http://192.168.119.128:5000/v3/auth/tokens"
    result = requests.post(url, data=json.dumps(data))
    # 返回的token在 response header 里面
    return result
# 注销project范围token
def token_project_del(domain_token,project_token):
    token_project_del_url = "http://192.168.119.128:5000/v3/auth/tokens"
    headers = {}
    headers["X-Auth-Token"] = domain_token
    headers["X-Subject-Token"] = project_token
    result = requests.delete(token_project_del_url, headers=headers)
    return result
# 注销domain范围token
def token_domain_del(domain_token):
    token_domain_del_url = "http://192.168.119.128:5000/v3/auth/tokens"
    headers = {}
    headers["X-Auth-Token"] = domain_token
    headers["X-Subject-Token"] = domain_token
    result = requests.delete(token_domain_del_url, headers=headers)
    return result
# 列出user
def users_list(domain_token):
    url = "http://192.168.119.128:5000/v3/users"
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result
# 创建users
def users_create(domain_token,username,password,description,email,role_id,project_id):
    url = 'http://192.168.119.128:5000/v3/users'
    data = {
        "user": {
            "enabled": True,
            "name": username,
            "password": password,
            "description": description,
            "email": email,
            "role_id": role_id,
            "project_id": project_id,
        }
    }
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result
# 显示users的详细信息
def users_info(domain_token,userid):
    url = "http://192.168.119.128:5000/v3/users/%s"%(userid)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result
# 更新users
def users_update(domain_token,username,description,email,userid,project_id):
    url = "http://192.168.119.128:5000/v3/users/%s"%(userid)
    data = {
        "user": {
            "name":username,
            "description":description,
            "email":email,
            "project_id":project_id
        }
    }
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.patch(url, data=json.dumps(data), headers=headers)
    return result

# 删除users
def users_del(domain_token,userid):
    url = "http://192.168.119.128:5000/v3/users/%s"%(userid)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.delete(url, headers=headers)
    return result
# 列出groups
def groups_list(domain_token):
    url = "http://192.168.119.128:5000/v3/groups"
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result

# 显示group的详细信息
def groups_info(domain_token,group_id):
    url = "http://192.168.119.128:5000/v3/groups/%s"%(group_id)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result
# 创建groups
def groups_create(domain_token,description,username):
    url = "http://192.168.119.128:5000/v3/groups"
    data = {
        "group": {
            "description": description,
            "name": username
        }
    }
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result
# 更新groups
def groups_update(domain_token,username,description,groupid):
    url = "http://192.168.119.128:5000/v3/groups/%s"%(groupid)
    data = {
        "group": {
            "description": description,
            "name": username
        }
    }
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.patch(url, data=json.dumps(data), headers=headers)
    return result
# 删除groups
def groups_del(domain_token,groupid):
    url = "http://192.168.119.128:5000/v3/groups/%s"%(groupid)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.delete(url, headers=headers)
    return result
# 列出groups中的user
def groups_user(domain_token,groupid):
    url = "http://192.168.119.128:5000/v3/groups/%s/users"%(groupid)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result
# 将users添加到groups
def users_add_group(domain_token,groupid,userid):
    url = "http://192.168.119.128:5000/v3/groups/%s/users/%s"%(groupid, userid)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.put(url, headers=headers)
    return result
# 从groups中删除users
def groups_del_user(domain_token,groupid,userid):
    url = "http://192.168.119.128:5000/v3/groups/%s/users/%s"%(groupid,userid)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.delete(url, headers=headers)
    return result
# 列出roles
def roles_list(domain_token):
    url = "http://192.168.119.128:5000/v3/roles"
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result
# 创建roles
def roles_create(domain_token,description,rolename):
    url = "http://192.168.119.128:5000/v3/roles"
    data = {
        "role": {
            "description": description,
            "name":rolename
        }
    }
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result
# 更新roles
def roles_update(domain_token,description,rolename,roleid):
    url = "http://192.168.119.128:5000/v3/roles/%s"%(roleid)
    data = {
        "role": {
            "description": description,
            "name": rolename
        }
    }
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.patch(url, data=json.dumps(data), headers=headers)
    return result
# 删除roles
def roles_del(domain_token,roleid):
    url = "http://192.168.119.128:5000/v3/roles/%s"%(roleid)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.delete(url, headers=headers)
    return result
# 列出projects
def projects_list(domain_token):
    url = "http://192.168.119.128:5000/v3/projects"
    headers = {}
    #print(domain_token)
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result
# 创建projects
def projects_create(domain_token,name,description):
    url = 'http://192.168.119.128:5000/v3/projects'
    data = {
        "project": {
            "description": description,
            "enabled": True,
            "is_domain": False,
            "name": name
        }
    }
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result
# 显示projects详细信息
def projects_info(domain_token,project_id):
    url = "http://192.168.119.128:5000/v3/projects/%s"%(project_id)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.get(url, headers=headers)
    return result
# 更新projects
def projects_update(domain_token,project_id,description, project_name):
    url = "http://192.168.119.128:5000/v3/projects/%s"%(project_id)
    data = {
        "project": {
            "description": description,
            "name": project_name,
        }
    }
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.patch(url, data=json.dumps(data), headers=headers)
    return result
# 删除projects
def projects_del(domain_token,project_id):
    url = "http://192.168.119.128:5000/v3/projects/%s"%(project_id)
    headers = {}
    headers["X-Auth-Token"] = domain_token
    result = requests.delete(url, headers=headers)
    return result





# 列出servers
def servers_list(project_token):
    url = "http://192.168.119.128:8774/v2.1/servers/detail"
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result

# 列出可用image
def images_list(project_token):
    url = "http://192.168.119.128:9292/v2/images"
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result

# 列出可用flavor
def flavor_list(project_token):
    url = "http://192.168.119.128:8774/v2.1/flavors/detail"
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result

# 创建servers
def servers_create(project_token,servername,imageid,flavorid):
    url = "http://192.168.119.128:8774/v2.1/servers"
    data = {
        "server": {
            "name": servername,
            "imageRef": imageid,
            "flavorRef": "http://192.168.119.128:8774/v2.1/flavors/%s"%(flavorid)
        }
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result

# 显示servers详细信息
def servers_info( project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s"%(serverid)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result

# 删除servers
def servers_del(project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s"%(serverid)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.delete(url, headers=headers)
    return result

# 显示flavor详细信息
def flavor_info(project_token,flavorid):
    url = "http://192.168.119.128:8774/v2.1/flavors/%s"%(flavorid)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result

# 启动servers
def servers_start( project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s/action"%(serverid)
    data = {
        "os-start" : 'null'
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result

# 重新启动servers
def servers_reboot(project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s/action"%(serverid)
    data = {
        "reboot" : {
            "type" : "HARD"
        }
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result

# 暂停servers
def servers_pause(project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s/action"%(serverid)
    data = {
        "pause": 'null'
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result

# 取消暂停的servers
def servers_unpause(project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s/action"%(serverid)
    data = {
        "unpause": 'null'
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result

# 挂起servers
def servers_suspend(project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s/action"%(serverid)
    data = {
        "suspend": 'null'
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result
# 恢复挂起的servers
def servers_resume_suspended(project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s/action"%(serverid)
    data = {
        "resume": 'null'
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result

# 创建servers的快照
def servers_snapshot( project_token,serverid,shotname):
    url = "http://192.168.119.128:8774/v2.1/servers/%s/action"%(serverid)
    data = {
        "createImage" : {
            "name" : shotname
        }
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result
# 关闭servers
def servers_stop(project_token,serverid):
    url = "http://192.168.119.128:8774/v2.1/servers/%s/action"%(serverid)
    data = {
        "os-stop" : 'null'
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result



# 创建镜像分为以下两个步骤：1.创建镜像位置 2.上传本地镜像

# 创建镜像位置
def image_create( imagename,container_format,disk_format,description,project_token):
    url = "http://192.168.119.128:9292/v2/images"
    data = {
        "owner": "0793c75e5f3a484fb7d9e4146f461595",    # 项目标识
        "container_format": container_format,
        "disk_format": disk_format,
        "name": imagename,
        "description": description
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.post(url, data=json.dumps(data), headers=headers)
    return result

# /home/cirros-0.4.0-x86_64-disk.img

# 上传本地镜像
def image_upload(path,project_token,imageid):
    url = "http://192.168.119.128:9292/v2/images/%s/file"%(imageid)
    data = {
        'file': path
    }
    headers = {}
    headers["X-Auth-Token"] = project_token
    headers["Content-Type"] = "application/octet-stream"
    result = requests.put(url, data=json.dumps(data), headers=headers)
    return result

# 上传本地镜像
def imageupload(data,project_token,imageid):
    url = "http://192.168.119.128:9292/v2/images/%s/file"%(imageid)
    headers = {}
    headers["X-Auth-Token"] = project_token
    headers["Content-Type"] = "application/octet-stream"
    result = requests.put(url, data, headers=headers)
    return result

# 显示images信息
def images_info(imageid,project_token):
    url = "http://192.168.119.128:9292/v2/images/%s"%(imageid)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result
# 删除images
def images_del(imageid,project_token):
    url = "http://192.168.119.128:9292/v2/images/%s"%(imageid)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.delete(url, headers=headers)
    return result



# 定义登录视图函数
def login(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            request.session["userName"] = username
            domain_res = get_domain_token(username,password)
            # 获得了domain_token
            # print("domain_token"+str(domain_res))
            if domain_res.status_code == 201:
                request.session["domain_token"] = domain_res.headers.get("X-Subject-Token")
                #print(domain_res.headers.get("X-Subject-Token"))
                # 通过domain_token获得project_token
                project_res = get_project_token(request.session.get("domain_token",None))
                #print(project_res.headers)
                request.session["project_token"] = project_res.headers.get("X-Subject-Token")
                #print(project_res.headers.get("X-Subject-Token"))
                return redirect('/wyh0282/project')
            else:
                return render(request, 'wyh0282/login.html', {'form': form,
                                                              'message': '登录失败，域名，账号，或密码错误！'})
    else:
        form = LoginForm()
        return render(request,'wyh0282/login.html',{'form':form})

@xframe_options_exempt
def projectlist(request):
    return render(request, 'wyh0282/projectlist.html')

@xframe_options_exempt
def userlist(request):
    return render(request, 'wyh0282/userlist.html')
#登出功能视图函数
def loginout(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res", None)
    if project_list:
        return render(request, 'wyh0282/project.html')
    else:
        project_tokenresp = token_project_del(domain_token,project_token)
        domain_tokenresp = token_domain_del(domain_token)
        if project_tokenresp.status_code and domain_tokenresp.status_code == 204:
            return redirect('/wyh0282/login/')
        else:
            return render(request,'wyh0282/project.html')
#定义登录进来项目视图函数
#返回iframe中的视图
def index(request):
    domain_token = request.session.get("domain_token",None)
    project_token = request.session.get("project_token",None)
    if not (domain_token and project_token):
        #print("!!!!!!")
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res",None)
    if project_list:
        return render(request,'wyh0282/project.html')
    else:
        #print("xxxxxx")
        resp = projects_list(project_token)
        # resp = projects_list(domain_token)
        #print(resp.status_code)
        if resp.status_code == 200:
            request.session["project_list"] = resp.json()
            return render(request, 'wyh0282/index.html')
        else:
            return redirect('/wyh0282/login/')
#html文件中ifram加载的页面
def livingExample(request):
    return render(request, 'wyh0282/livingExample.html')

def projectLivingExample(request):
    return render(request, 'wyh0282/projectLivingExample.html')

#实例
def mServerLists(request):
    return render(request, 'wyh0282/mServerLists.html')

#实例的json数据
def server_json(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = servers_list(project_token)
    r = []
    if resp.status_code == 200:
        result = resp.json()['servers']
        for i in range(len(result)):
            image_id = result[i].get("image").get("id")
            resp = images_info(image_id, domain_token)
            image_name= resp.json().get("name")
            result[i]["image_name"] = image_name
            ip = result[i].get("addresses").get("provider")[0].get("addr")
            result[i]["ip"] = ip
            flavor_id = result[i].get("flavor").get("id")
            flavor = flavor_info(project_token,flavor_id)

            original_name = flavor.json().get("flavor").get("name")
            result[i]["original_name"] = original_name
            status =  result[i].get("status")
            if status == "ACTIVE":
                result[i]["status"]="活动"
            else:
                result[i]["status"]="关机"

            power_state = result[i].get("OS-EXT-STS:power_state")
            if power_state == 1:
                result[i]["power_state"]="正在运行"
            else:
                result[i]["power_state"]="关闭"
            task_state = result[i].get("OS-EXT-STS:task_state")
            if task_state is None:
                result[i]["task_state"] = "无"
            else:
                result[i]["task_state"] = "有"
            created = result[i].get("created")
            data = datetime.datetime.now()
            now_year = data.year
            now_month = data.month
            created_year = created[0:4]
            created_month_index = created[5:6]
            created_month_last_index = created[6:7]
            created_month = 0
            year = 0
            month = 0
            if int(created_month_index) == 0:
                created_month = int(created_month_last_index)
            else:
                created_month = 10 + int(created_month_last_index)
            if now_month > created_month:
                year = int(now_year) - int(created_year)
                month = now_month - created_month
            else:
                year = int(now_year) - int(created_year)-1
                month = created_month - now_month + 2
            data = str(year) + " 年" + str(month) + " 月"
            result[i]["created_date"] = data
            keyPair = result[i]["key_name"]
            if keyPair is None:
                result[i]["key_name"] = "空"
        r = result
        re = {"code": 0, "msg": "success", "count": 100, "data": r}
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#启动实例
def serverStart(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = servers_start(project_token, id)
    if resp.status_code == 202:
        re = {"code": 1, "msg": "启动成功！"}
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    re = {"code": 0, "msg": "启动失败！"}
    return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#结束实例
def serverEnd(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = servers_stop(project_token, id)
    if resp.status_code == 202:
        re = {"code": 1, "msg": "结束成功！"}
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    re = {"code": 0, "msg": "结束失败！"}
    return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#重新启动实例
def reServerStart(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = servers_reboot(project_token, id)
    if resp.status_code == 202:
        re = {"code": 1, "msg": "重新启动成功！"}
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    re = {"code": 0, "msg": "重新启动失败！"}
    return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#暂停实例
def serverSuspend(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = servers_pause(project_token, id)
    if resp.status_code == 202:
        re = {"code": 1, "msg": "暂停成功！"}
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    re = {"code": 0, "msg": "暂停失败！"}
    return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#恢复暂停实例
def noServerSuspend(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = servers_unpause(project_token, id)
    if resp.status_code == 202:
        re = {"code": 1, "msg": "取消暂停成功"}
        # 返回符合layui的json数据
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    re = {"code": 0, "msg": "取消暂停失败！"}
    # 返回符合layui的json数据
    return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#挂起实例
def serverHang(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp =servers_suspend(project_token, id)
    if resp.status_code == 202:
        re = {"code": 1, "msg": "挂起成功"}
        # 返回符合layui的json数据
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    re = {"code": 0, "msg": "挂起失败！"}
    # 返回符合layui的json数据
    return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#挂起恢复实例
def resumePendingServer(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = servers_resume_suspended(project_token, id)
    if resp.status_code == 202:
        re = {"code": 1, "msg": "恢复成功"}
        # 返回符合layui的json数据
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    re = {"code": 0, "msg": "恢复失败！"}
    # 返回符合layui的json数据
    return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#创建实例快照的html页面
def serverSnapshotHtml(request):
    create_server_id = request.GET.get("server_id")
    request.session["create_server_id"] = create_server_id
    return render(request, 'wyh0282/serverSnapshotHtml.html')

#真正创建实例快照
def serverSnapshot(request):
    id = request.session.get("create_server_id", None)
    project_token = request.session.get("project_token", None)
    if request.method == "POST":
        shotname = str(request.POST.getlist("describe")[0])
        resp = servers_snapshot(project_token,id,shotname)
        if resp.status_code == 202:
            re = {"code": 1, "msg": "创建成功"}
            # 返回符合layui的json数据
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        re = {"code": 0, "msg": "创建失败！"}
        # 返回符合layui的json数据
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#实例的控制台页面
def serverConsole(request):
    return render(request, 'wyh0282/console.html')
#实例操作的控制台
def operationConsole(request):
    return render(request, 'wyh0282/perationConsole.html')

#显示项目信息
def serverMessage(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    server_id = request.GET.get("server_id")
    resp = servers_info(project_token,server_id)
    #print(resp.status_code)
    if resp.status_code == 200:
        #print(resp.json())
        request.session["server"] = resp.json()
        return render(request, 'wyh0282/serverMessage.html')


#角色管理下的项目
def mProjectLists(request):
    return render(request, 'wyh0282/mProjectLists.html')
#弹出框的页面
def projectAdd(request):
    return render(request, 'wyh0282/projectAdd.html')
#编辑操作
def projectEdit(request):
    id = request.GET.get("project_id")
    domain_token = request.session.get("domain_token", None)
    resp = projects_info(domain_token, id)
    if resp.status_code == 200:
        request.session["project"] = resp.json()
    return render(request, 'wyh0282/projectEdit.html')
#删除操作
#删除项目
def projectDelete(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    id = request.GET.get("project_id")
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        respones = projects_del(project_token,id)
        #print(respones.status_code)
        if respones.status_code == 204:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false",}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#创建项目
def projectCreate(request):
    #print("1111")
    if request.method == "POST":
        porjectName = str(request.POST.getlist("projectName")[0])
        projectDescribe = str(request.POST.getlist("projectDescribe")[0])
        domain_token = request.session.get("domain_token", None)
        project_token = request.session.get("project_token", None)
        domain_res = projects_create(domain_token,porjectName,projectDescribe)
        #print(domain_res)
        if domain_res.status_code == 201:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "false", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
#更新项目
def projectUpdate(request):
    if request.method == "POST":
        porjectName = str(request.POST.getlist("projectName")[0])
        projectDescribe = str(request.POST.getlist("projectDescribe")[0])
        projectupdateid = str(request.POST.getlist("id")[0])
        domain_token = request.session.get("domain_token", None)
        domain_res = projects_update(domain_token,projectupdateid,projectDescribe,porjectName)
        if domain_res.status_code == 200:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "false", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
#显示项目的详细信息
def projectMessage(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    project_id = request.GET.get("project_id")
    resp = projects_info(domain_token,project_id)
    if resp.status_code == 200:
        #print(resp.json())
        request.session["project"] = resp.json()
        return render(request, 'wyh0282/projectMessage.htmL')


#images的json数据
def images_json(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = images_list(project_token)
    if resp.status_code == 200:
        result = resp.json()['images']
        for i in range(len(result)):
            project_id = result[i].get("owner")
            project_name = projects_info(domain_token,project_id).json().get("project").get("name")
            result[i]["owner"] = project_name
            size = 0
            if result[i]["size"] is None:
                size = 0
            else:
                size = int(result[i]["size"])
            result[i]["size"] = str(round(size/1048576,2)) + "MB"
        re = {"code": 0, "msg": "success", "count": 100, "data": result}
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    # 弹出框的页面
#镜像
def mImagesLists(request):
    return render(request, 'wyh0282/mImagesLists.html')
#弹出框的页面
def imagesAdd(request):
    return render(request, 'wyh0282/imagesAdd.html')
#上传镜像页面
def imagesUp(request):
    id = request.GET.get("image_id")
    #print(id)
    request.session["image_id"] = id
    return render(request, 'wyh0282/imagesUp.html')
#真正上传镜像页面
def image_up(request):
    if request.method == "POST":
        path = str(request.POST.getlist("imagePath")[0])
        project_token = request.session.get("project_token", None)
        imageid = request.session.get("image_id", None)
        res = image_upload(path,project_token,imageid)
        if res.status_code == 204:
            re = {"code": 1, "msg": "上传映像成功！"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "上传映像失败"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#真正上传镜像页面
def imageUp1(request):
    if request.method == "POST":
        file_path = str(request.POST.getlist("file_path")[0])
        file = open(file_path,"rb").read()
        project_token = request.session.get("project_token", None)
        imageid = request.session.get("image_id", None)
        res = imageupload(file, project_token, imageid)
        print(res.status_code)
    if res.status_code == 204:
        re = {"code": 1, "msg": "上传映像成功！"}
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "上传映像失败"}
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#编辑操作
def imagesEdit(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    resp = projects_info(domain_token, id)
    if resp.status_code == 200:
        request.session["project"] = resp.json()
    return render(request, 'wyh0282/imagesEdit.html')

#删除镜像
def imagesDelete(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    id = request.GET.get("image_id")
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        respones = images_del(id,project_token)
        #print(respones.status_code)
        if respones.status_code == 204:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false",}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#创建镜像
def imagesCreate(request):
    #print("1111")
    if request.method == "POST":
        image_name = str(request.POST.getlist("image_name")[0])
        #容器格式
        container_format = str(request.POST.getlist("container_format")[0])
        #磁盘格式qcow2
        disk_format = str(request.POST.getlist("disk_format")[0])
        description = str(request.POST.getlist("description")[0])
        description = str(request.POST.getlist("description")[0])
        domain_token = request.session.get("domain_token", None)
        project_token = request.session.get("project_token", None)
        domain_res = image_create(image_name,container_format,disk_format,description,project_token)
        if domain_res.status_code == 201:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "false", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
#更新镜像
def imagesUpdate(request):
    if request.method == "POST":
        porjectName = str(request.POST.getlist("projectName")[0])
        projectDescribe = str(request.POST.getlist("projectDescribe")[0])
        projectupdateid = str(request.POST.getlist("id")[0])
        domain_token = request.session.get("domain_token", None)
        domain_res = projects_update(domain_token,projectupdateid,projectDescribe,porjectName)
        if domain_res.status_code == 200:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "false", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
#显示镜像
def showImage(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    image_id = request.GET.get("image_id")
    resp = images_info(image_id,domain_token)
    if resp.status_code == 200:
        #print(resp.json())
        request.session["image"] = resp.json()
        return render(request, 'wyh0282/showImage.htmL')

#flavor数据显示页面
def mFlavorLists(request):
    return render(request, 'wyh0282/mFlavorLists.html')
#flavor的json数据
def flavor_json(request):
    project_token = request.session.get("project_token", None)
    resp = flavor_list(project_token)
    print(resp.json())
    if resp.status_code == 200:
        result = resp.json()['flavors']
        for i in range(len(result)):
            result[i]["disk"] = str(result[i].get("disk"))+ "GB"
            result[i]["OS-FLV-EXT-DATA:ephemeral"] = str(result[i].get("OS-FLV-EXT-DATA:ephemeral")) + "GB"
            ram = (result[i].get("ram"))
            if ram < 1024:
                result[i]["ram"] = str(ram) + "MB"
            else:
                result[i]["ram"] = str(round(ram/1024,0)) + "GB"
        re = {"code": 0, "msg": "success", "count": 100, "data": result}
        #返回符合layui的json数据
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")

#角色管理下的角色
def mRoleLists(request):
    return render(request, 'wyh0282/mRoleLists.html')
#获得role的json数据
def role_json(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = roles_list(domain_token)
    if resp.status_code == 200:
        #print(resp.json())
        result = resp.json()['roles']
        #print(result)
        #resp = servers_info(project_token, serverid)
        #if resp.status_code == 200:
            #request.session["servers_detail"] = resp.json()
        re = {"code": 0, "msg": "success", "count": 100, "data": result}
        #返回符合layui的json数据
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#普通方法的
#弹出框的页面
def roleAdd(request):
    return render(request, 'wyh0282/roleAdd.html')
#编辑操作
def roleEdit(request):
    id = request.GET.get("id")
    request.session["role_id"] = id
    return render(request, 'wyh0282/roleEdit.html')
#删除角色
def roleDelete(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    id = request.GET.get("id")
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        respones = roles_del(project_token,id)
        #print(respones.status_code)
        if respones.status_code == 204:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false",}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#创建角色
def roleCreate(request):
    if request.method == "POST":
        roleName = str(request.POST.getlist("roleName")[0])
        roleDescribe = str(request.POST.getlist("roleDescribe")[0])
        domain_token = request.session.get("domain_token", None)
        project_token = request.session.get("project_token", None)
        domain_res = roles_create(domain_token,roleName,roleDescribe)
        #print(domain_res)
        if domain_res.status_code == 201:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "false", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
#更新角色
def roleUpdate(request):
    if request.method == "POST":
        roleName = str(request.POST.getlist("roleName")[0])
        roleDescribe = str(request.POST.getlist("roleDescribe")[0])
        id = request.session.get("role_id", None)
        domain_token = request.session.get("domain_token", None)
        print(id)
        domain_res = roles_update(domain_token,roleDescribe,roleName,id)
        #print(domain_res.status_code)
        if domain_res.status_code == 200:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "false", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#角色管理下的用户
def mUserLists(request):
    return render(request, 'wyh0282/mUserLists.html')
#获得user的json数据
def user_json(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = users_list(domain_token)
    if resp.status_code == 200:
        #print(resp.json())
        result = resp.json()['users']
        for i in range(len(result)):  # 第二个实例
            domain_id = result[i].get("domain_id")
            domain_msg = domain_info(domain_token, domain_id)
            domain_name = domain_msg.json()["domain"]["name"]
            result[i]["domain_name"] = domain_name
        #print(result)
        re = {"code": 0, "msg": "success", "count": 100, "data": result}
        #返回符合layui的json数据
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#弹出框的页面
def userAdd(request):
    return render(request, 'wyh0282/userAdd.html')
#编辑操作
def userEdit(request):
    id = request.GET.get("id")
    #print(id)
    domain_token = request.session.get("domain_token", None)
    resp = users_info(domain_token,id)
    user = resp.json()
    project_id = user.get("user").get("project_id")
    project = projects_info(domain_token,project_id).json()
    request.session["project"] = project
    request.session["user"] = user
    #print(resp.json())
    request.session["user_id"] = id
    return render(request, 'wyh0282/userEdit.html')
#删除用户
def userDelete(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    id = request.GET.get("id")
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        respones = users_del(project_token,id)
        #print(respones.status_code)
        if respones.status_code == 204:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false",}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#创建用户
def userCreate(request):
    if request.method == "POST":
        userName = str(request.POST.getlist("userName")[0])
        userPwd = str(request.POST.getlist("userPwd")[0])
        userPwd2 = str(request.POST.getlist("userPwd2")[0])
        userDescribe = str(request.POST.getlist("userDescribe")[0])
        userEmail = str(request.POST.getlist("userEmail")[0])
        project_id = str(request.POST.getlist("projectId")[0])
        role_id = str(request.POST.getlist("roleId")[0])
        domain_token = request.session.get("domain_token", None)
        #获取角色数据
        resp = roles_list(domain_token)
        if resp.status_code == 200:
            rs = resp.json()['roles']
            for i in range(len(rs)):  # 第二个实例
                if rs[i].get("name") == role_id:
                    role_id = rs[i].get("id")
                    break
        resp1 = projects_list(domain_token)
        if resp1.status_code == 200:
            rs = resp1.json()['projects']
            for i in range(len(rs)):  # 第二个实例
                if rs[i].get("name") == project_id:
                    project_id = rs[i].get("id")
                    break
        #print(project_id)
        if userPwd2 != userPwd:
            re = {"code": 0, "msg": "两次密码不一致", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        wrongRegex = rerule.compile(r"\"?([-a-zA-Z0-9.?{}]+@\w+\.\w+)\"?")
        if rerule.match(wrongRegex, userEmail) is None:
            re = {"code": 0, "msg": "邮箱不合法，请重新输入！", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        if len(userEmail) < 3 or len(userEmail) > 20:
            re = {"code": 0, "msg": "邮箱应在3-20位之间，请重新输入！", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        domain_res = users_create(domain_token, userName, userPwd, userDescribe, userEmail, role_id, project_id)
        # print(domainusers_create_res)
        if domain_res.status_code == 201:
            re = {"code": 1, "msg": "创建成功！"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "创建失败！", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        re = {"code": 0, "msg": "创建失败", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
#更新用户
def userUpdate(request):
    if request.method == "POST":
        userName = str(request.POST.getlist("userName")[0])
        userDescribe = str(request.POST.getlist("userDescribe")[0])
        userEmail = str(request.POST.getlist("userEmail")[0])
        project_id = str(request.POST.getlist("projectId")[0])
        #role_id = str(request.POST.getlist("roleId")[0])
        domain_token = request.session.get("domain_token", None)
        user_id = request.session.get("user_id", None)
        resp1 = projects_list(domain_token)
        if resp1.status_code == 200:
            rs = resp1.json()['projects']
            for i in range(len(rs)):  # 第二个实例
                if rs[i].get("name") == project_id:
                    project_id = rs[i].get("id")
                    break
        #print(project_id)
        wrongRegex = rerule.compile(r"\"?([-a-zA-Z0-9.?{}]+@\w+\.\w+)\"?")
        if rerule.match(wrongRegex, userEmail) is None:
            re = {"code": 0, "msg": "邮箱不合法，请重新输入！", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        if len(userEmail) < 3 or len(userEmail) > 20:
            re = {"code": 0, "msg": "邮箱应在3-20位之间，请重新输入！", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        domain_res = users_update(domain_token,userName,userDescribe,userEmail,user_id,project_id)
        #print(domain_res.status_code)
        if domain_res.status_code == 200:
            re = {"code": 1, "msg": "更新成功！"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "更新失败！", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        re = {"code": 0, "msg": "更新失败！", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
#显示用户信息
def userMessage(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_id = request.GET.get("user_id")
    resp = users_info(domain_token,user_id)
    if resp.status_code == 200:
        #print(resp.json())
        request.session["user"] = resp.json()
        return render(request, 'wyh0282/userMessage.htmL')

#角色管理下的组
def mGroupLists(request):
    return render(request, 'wyh0282/mGroupLists.html')
#获得组的json数据
def group_json(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = groups_list(domain_token)
    if resp.status_code == 200:
        #print(resp.json())
        result = resp.json()['groups']
        #print(result)
        #resp = servers_info(project_token, serverid)
        #if resp.status_code == 200:
            #request.session["servers_detail"] = resp.json()
        re = {"code": 0, "msg": "success", "count": 100, "data": result}
        #返回符合layui的json数据
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#弹出框的页面
def groupAdd(request):
    return render(request, 'wyh0282/groupAdd.html')
#编辑操作
def groupEdit(request):
    id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    request.session["group_id"] = id
    return render(request, 'wyh0282/groupEdit.html')
#删除组
def groupDelete(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    id = request.GET.get("id")
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        respones = groups_del(project_token,id)
        #print(respones.status_code)
        if respones.status_code == 204:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false",}
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#创建组
def groupCreate(request):
    if request.method == "POST":
        groupName = str(request.POST.getlist("groupName")[0])
        groupDescribe = str(request.POST.getlist("groupDescribe")[0])
        domain_token = request.session.get("domain_token", None)
        project_token = request.session.get("project_token", None)
        domain_res = groups_create(domain_token,groupName,groupDescribe)
        #print(domain_res)
        if domain_res.status_code == 201:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "false", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
#更新组
def groupUpdate(request):
    if request.method == "POST":
        groupName = str(request.POST.getlist("groupName")[0])
        groupDescribe = str(request.POST.getlist("groupDescribe")[0])
        id = request.session.get("group_id", None)
        domain_token = request.session.get("domain_token", None)
        #print(id)
        domain_res = groups_update(domain_token,groupDescribe,groupName,id)
        #print(domain_res.status_code)
        if domain_res.status_code == 200:
            re = {"code": 1, "msg": "success"}
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
        else:
            re = {"code": 0, "msg": "false", }
            return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")
    else:
        re = {"code": 0, "msg": "false", }
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#组下面的用户管理
def manageUser(request):
    group_id = request.GET.get("id")
    domain_token = request.session.get("domain_token", None)
    group = groups_info(domain_token,group_id)
    request.session["group"] = group.json()
    request.session["m_group_id"] = group_id
    return render(request, 'wyh0282/manageUser.html')

#组下面的用户json数据
def groupUserJson(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    group_id = request.session.get("m_group_id", None)
    resp = groups_user(domain_token,group_id)
    #print(resp.json())
    if resp.status_code == 200:
        result = resp.json()['users']
        re = {"code": 0, "msg": "success", "count": 100, "data": result}
        #返回符合layui的json数据
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")

#展示没有加入组的用户json数据
def noGroupUserJson(request):
    domain_token = request.session.get("domain_token", None)
    resp = users_list(domain_token)
    r = []
    if resp.status_code == 200:
        result = resp.json()['users']
        for i in range(len(result)):
            if(result[i].__contains__("group_id")):
                continue
            else:
                r.append(result[i])
        re = {"code": 0, "msg": "success", "count": 100, "data": r}
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")

#添加用户页面
def noGroupUser(request):
    return render(request, 'wyh0282/noGroupUser.html')

#组里面加入用户
def groupAddUser(request):
    group_id = request.session.get("m_group_id", None)
    domain_token = request.session.get("domain_token", None)
    user_id = request.GET.get("user_id")
    resp = users_add_group(domain_token, group_id,user_id)
    if resp.status_code == 200:
        re = {"code": 1, "msg": "success", "count": 100}
        #返回符合layui的json数据
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")


#组里面删除用户
def groupDeleteUser(request):
    user_id = request.GET.get("id")
    group_id = request.session.get("m_group_id")
    domain_token = request.session.get("domain_token", None)
    resp = groups_del_user(domain_token, group_id, user_id)
    #print(resp.status_code)
    if resp.status_code == 204:
        re = {"code": 1, "msg": "success", "count": 100}
        # 返回符合layui的json数据
        return HttpResponse(json.dumps(re), content_type="application/json,charset=utf-8")



#定义项目视图函数
def project_list(request):
    domain_token = request.session.get("domain_token",None)
    project_token = request.session.get("project_token",None)
    if not (domain_token and project_token):
        #print("!!!!!!")
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res",None)
    if project_list:
        return render(request,'wyh0282/project.html')
    else:
        #print("xxxxxx")
        resp = projects_list(project_token)
        # resp = projects_list(domain_token)
        #print(resp.status_code)
        if resp.status_code == 200:
            request.session["project_list"] = resp.json()
            return render(request, 'wyh0282/main.html')
        else:
            return redirect('/wyh0282/login/')
#获得项目json数据
def indexData(request):
    domain_token = request.session.get("domain_token",None)
    project_token = request.session.get("project_token",None)
    if not (domain_token and project_token):
        #print("!!!!!!")
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res",None)
    if project_list:
        return render(request,'wyh0282/project.html')
    else:
        #print("xxxxxx")
        resp = projects_list(project_token)
        # resp = projects_list(domain_token)
        #print(resp.status_code)
        if resp.status_code == 200:
            #request.session["project_list"] = resp.json()
            result = resp.json()['projects']
            #obj = [{"code":0}, {"msg":"success"}, {"count":4}, {"data":result}];
            #print(result)
            #encodedjson = json.dumps(obj)
            #print(encodedjson)
            re = {"code": 0, "msg": "success", "count": 100, "data": result}
            #print(json.dumps(re))
            #返回符合layui的json数据
            return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
        else:
            return redirect('/wyh0282/login/')
#获得实例json数据
def livingExampleDatas(request):
    project_token = request.session.get("project_token",None)
    resp = servers_list(project_token)
    if resp.status_code == 200:
        #print(resp.json())
        result = resp.json()['servers']
        #print(result[0])
        #resp = servers_info(project_token, serverid)
        #if resp.status_code == 200:
            #request.session["servers_detail"] = resp.json()
        re = {"code": 0, "msg": "success", "count": 100, "data": result}
        #返回符合layui的json数据
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")
#获取domain信息
#def domainInfo(request):
    #domain_token = request.session.get("domain_token", None)



#项目数据
def project_json(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    resp = projects_list(project_token)
    r=[]
    if resp.status_code == 200:
        result = resp.json()['projects']
        for i in range(len(result)):  # 第二个实例
            domain_id = result[i].get("domain_id")
            domain_msg = domain_info(domain_token, domain_id)
            domain_name = domain_msg.json()["domain"]["name"]
            result[i]["domain_name"] = domain_name

        re = {"code": 0, "msg": "success", "count": 100, "data": result}
        #返回符合layui的json数据
        return HttpResponse(json.dumps(re),content_type="application/json,charset=utf-8")


#删除项目
def project_delete(request,id):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        respones = projects_del(domain_token,id)
        if respones.status_code == 204:
            messages.info(request, '删除成功！')
            return redirect('/wyh0282/projectlist/')
        else:
            return render(request, 'wyh0282/projectlist.html' )
#创建项目
def projects_creates(request):
    if request.method == "POST":
        form = ProjectcreateForm(request.POST)
        if form.is_valid():
            projectname = form.cleaned_data.get('projectName')
            description = form.cleaned_data.get('projectDescribe')
            #print(projectname)
            #print(description)
            domain_token = request.session.get("domain_token", None)
            domain_res = projects_create(domain_token,projectname,description)
            if domain_res.status_code == 201:
                messages.info(request, '创建成功！')
                return redirect('/wyh0282/projectlist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = ProjectcreateForm()
    return render(request,'wyh0282/projectcreate.html',{'form':form})
#列举项目详细信息
def project_detail(request,projectid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res", None)
    if project_list:
        return render(request, 'wyh0282/projectlist.html')
    else:
        resp = projects_info(domain_token,projectid)
        if resp.status_code == 200:
            request.session["project_list"] = resp.json()
            return render(request, 'wyh0282/projectinfo.html')
        else:
            return redirect('/wyh0282/projectlist/')
#更新项目信息
def project_update(request,projectupdateid):
    if request.method == "POST":
        form = ProjectupdateForm(request.POST)
        if form.is_valid():
            projectname = form.cleaned_data.get('projectname')
            description = form.cleaned_data.get('description')
            domain_token = request.session.get("domain_token", None)
            domain_res = projects_update(domain_token,projectupdateid,description,projectname)
            if domain_res.status_code == 200:
                messages.info(request, '更新成功！')
                return redirect('/wyh0282/projectlist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = ProjectupdateForm()
    return render(request,'wyh0282/projectupdate.html',{'form':form})
#列出用户
def user_list(request):
    domain_token = request.session.get("domain_token",None)
    project_token = request.session.get("project_token",None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res",None)
    if user_lists:
        return render(request,'wyh0282/project.html')
    else:
        resp = users_list(domain_token)
        if resp.status_code == 200:
            request.session["user_list"] = resp.json()
            return render(request,'wyh0282/userlist.html')
        else:
            return redirect('/wyh0282/login/')

#删除用户
def user_delete(request,userid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        res = users_del(domain_token,userid)
        if res.status_code == 204:
            messages.info(request, '删除成功！')
            return redirect('/wyh0282/userlist/')
        else:
            return render(request, 'wyh0282/projectlist.html' )
#添加用户
def user_create(request):
    if request.method == "POST":
        form = UsercreateForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get('user')
            description = form.cleaned_data.get('description')
            domain_token = request.session.get("domain_token", None)
            password = form.cleaned_data.get('password')
            email = form.cleaned_data.get('email')
            res = users_create(domain_token,name,password,description,email)
            if res.status_code == 201:
                messages.info(request, '创建成功！')
                return redirect('/wyh0282/userlist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = UsercreateForm()
    return render(request, 'wyh0282/usercreate.html', {'form': form})
#查看用户详细信息
def user_detail(request,userid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res", None)
    if project_list:
        return render(request, 'wyh0282/projectlist.html')
    else:
        resp = users_info(domain_token,userid)
        if resp.status_code == 200:
            request.session["user_list"] = resp.json()
            return render(request, 'wyh0282/userinfo.html')
        else:
            return redirect('/wyh0282/projectlist/')


#编辑用户
def user_update(request,userid):
    if request.method == "POST":
        form = UserupdateForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            description = form.cleaned_data.get('description')
            email = form.cleaned_data.get('email')
            domain_token = request.session.get("domain_token", None)
            res = users_update(domain_token,username,description,email,userid)
            if res.status_code == 200:
                messages.info(request, '编辑成功！')
                return redirect('/wyh0282/userlist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = UserupdateForm()
    return render(request, 'wyh0282/userupdate.html', {'form': form})
#列出组
def group_list(request):
    domain_token = request.session.get("domain_token",None)
    project_token = request.session.get("project_token",None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res",None)
    if user_lists:
        return render(request,'wyh0282/project.html')
    else:
        resp = groups_list(domain_token)
        if resp.status_code == 200:
            request.session["groups_list"] = resp.json()
            return render(request,'wyh0282/grouplist.html')
        else:
            return redirect('/wyh0282/login/')
#编辑组
def group_update(request,groupid):
    if request.method == "POST":
        form = GroupupdateForm(request.POST)
        if form.is_valid():
            groupname = form.cleaned_data.get('groupname')
            description = form.cleaned_data.get('description')
            domain_token = request.session.get("domain_token", None)
            res = groups_update(domain_token,groupname,description,groupid)
            if res.status_code == 200:
                messages.info(request, '更新成功！')
                return redirect('/wyh0282/grouplist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = GroupupdateForm()
    return render(request,'wyh0282/groupdate.html',{'form':form})
#添加组
def group_create(request):
    if request.method == "POST":
        form = GroupcreateForm(request.POST)
        if form.is_valid():
            groupname = form.cleaned_data.get('groupname')
            description = form.cleaned_data.get('description')
            domain_token = request.session.get("domain_token", None)
            res = groups_create(domain_token,description,groupname)
            if res.status_code == 201:
                messages.info(request, '创建成功！')
                return redirect('/wyh0282/grouplist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form =GroupcreateForm()
    return render(request,'wyh0282/projectcreate.html',{'form':form})
#删除组
def group_delete(request,groupid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        res = groups_del(domain_token,groupid)
        if res.status_code == 204:
            messages.info(request, '删除成功！')
            return redirect('/wyh0282/grouplist/')
        else:
            return render(request, 'wyh0282/projectlist.html' )
#列出组里面的用户
def group_user(request,groupid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res", None)
    if project_list:
        return render(request, 'wyh0282/projectlist.html')
    else:
        resp = groups_user(domain_token,groupid)
        if resp.status_code == 200:
            request.session["group_list"] = resp.json()
            return render(request, 'wyh0282/groupuser.html')
        else:
            return redirect('/wyh0282/projectlist/')
#将用户添加到组
def group_add(request,id):
    domain_token = request.session.get("domain_token",None)
    project_token = request.session.get("project_token",None)
    request.session['groupid'] = id
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res",None)
    if user_lists:
        return render(request,'wyh0282/project.html')
    else:
        resp = users_list(domain_token)
        if resp.status_code == 200:
            request.session["user_list"] = resp.json()
            return render(request,'wyh0282/groupuserlist.html')
        else:
            return redirect('/wyh0282/login/')
def group_users(request,id):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    groupid = request.session.get("groupid",None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = users_add_group(domain_token,groupid,id)
        if resp.status_code == 204:
            messages.info(request, '添加成功！')
            return render(request, 'wyh0282/grouplist.html')
        else:
            return redirect('/wyh0282/login/')
#删除组里面的用户
def group_deleteuser(request,id):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    groupid = request.session.get("groupid", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = groups_del_user(domain_token,groupid,id)
        if resp.status_code == 204:
            messages.info(request, '删除成功！')
            return render(request, 'wyh0282/grouplist.html')
        else:
            return redirect('/wyh0282/login/')
#列出角色
def role_list(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = roles_list(domain_token)
        if resp.status_code == 200:
            request.session["roles_list"] = resp.json()
            return render(request, 'wyh0282/roleslist.html')
        else:
            return redirect('/wyh0282/login/')
#添加角色
def role_create(request):
    if request.method == "POST":
        form = RolecreatForm(request.POST)
        if form.is_valid():
            rolename = form.cleaned_data.get('rolename')
            domain_token = request.session.get("domain_token", None)
            description = form.cleaned_data.get('description')
            res = roles_create(domain_token,description,rolename)
            if res.status_code == 201:
                messages.info(request, '创建成功！')
                return redirect('/wyh0282/rolelist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = RolecreatForm()
    return render(request, 'wyh0282/rolecreate.html', {'form': form})
#删除角色
def role_delete(request,id):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = roles_del(domain_token,id)
        if resp.status_code == 204:
            messages.info(request, '删除成功！')
            return redirect('/wyh0282/rolelist/')
        else:
            return render(request, 'wyh0282/projectlist.html')
#编辑角色
def role_update(request,id):
    if request.method == "POST":
        form = RoleUpdateForm(request.POST)
        if form.is_valid():
            rolename = form.cleaned_data.get('rolename')
            domain_token = request.session.get("domain_token", None)
            description = form.cleaned_data.get('description')
            res = roles_update(domain_token,description,rolename,id)
            if res.status_code == 200:
                messages.info(request, '更新成功！')
                return redirect('/wyh0282/rolelist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = RoleUpdateForm()
    return render(request, 'wyh0282/roleupdate.html', {'form': form})
#列出flavor
def flavors_list(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = flavor_list(project_token)

        if resp.status_code == 200:
            request.session["flavors_list"] = resp.json()
            return render(request, 'wyh0282/flavorlist.html')
        else:
            return redirect('/wyh0282/login/')
# 查看flavor详细信息
def flavors_detail(request,id):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res", None)
    if project_list:
        return render(request, 'wyh0282/projectlist.html')
    else:
        resp = flavor_info(project_token,id)
        if resp.status_code == 200:
            request.session["flavors_detail"] = resp.json()
            return render(request, 'wyh0282/flavorinfo.html')
        else:
            return redirect('/wyh0282/projectlist/')
# 列举server
def server_list(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = servers_list(project_token)
        if resp.status_code == 200:
            request.session["server_list"] = resp.json()
            return render(request, 'wyh0282/serverlist.html')
        else:
            return redirect('/wyh0282/login/')
# 列出可用image
def image_list(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = images_list(project_token)
        if resp.status_code == 200:
            request.session["images_list"] = resp.json()
            return render(request, 'wyh0282/imagelist.html')
        else:
            return redirect('/wyh0282/login/')
# 列出可用flavors
def list_flavor(request,imageid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    request.session['imageid'] = imageid
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = flavor_list(project_token)
        if resp.status_code == 200:
            request.session["list_flavor"] = resp.json()
            return render(request, 'wyh0282/listflavor.html')
        else:
            return redirect('/wyh0282/login/')
# 创建实例
def server_create(request,flavorid):
    if request.method == "POST":
        form = ServercreatForm(request.POST)
        if form.is_valid():
            servername = form.cleaned_data.get('servername')
            project_token = request.session.get("project_token", None)
            imageid = request.session.get("imageid",None)
            res = servers_create(project_token,servername,imageid,flavorid)
            if res.status_code == 202:
                messages.info(request, '创建成功！')
                return redirect('/wyh0282/serverlist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = ServercreatForm()
    return render(request, 'wyh0282/servercreate.html', {'form': form})
# 删除实例
def server_delete(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = servers_del(project_token,serverid)
        if resp.status_code == 204:
            messages.info(request, '删除成功！')
            return redirect('/wyh0282/serverlist/')
        else:
            return render(request, 'wyh0282/projectlist.html')
# 显示实例详细信息
def server_detail(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    project_list = request.session.get("project_res", None)
    if project_list:
        return render(request, 'wyh0282/projectlist.html')
    else:
        resp = servers_info(project_token,serverid)
        if resp.status_code == 200:
            request.session["servers_detail"] = resp.json()
            return render(request, 'wyh0282/serverinfo.html')
        else:
            return redirect('/wyh0282/projectlist/')

# 启动实例
def server_on(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = servers_start(project_token,serverid)
        if resp.status_code == 202:
            messages.info(request, '开启成功！')
            return redirect('/wyh0282/serverlist/')
        else:
            return render(request, 'wyh0282/projectlist.html')

# 启动实例
def server_run(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        #resp = servers_start(project_token,serverid)
        #print(project_token)
        #(serverid)
        resp = {"status_code":20}
        if resp.status_code == 202:
            messages.info(request, '开启成功！')
            return redirect('/wyh0282/serverlist/')
        else:
            return render(request, 'wyh0282/projectlist.html')
# 重启实例
def server_restart(request,serverid):
        domain_token = request.session.get("domain_token", None)
        project_token = request.session.get("project_token", None)
        if not (domain_token and project_token):
            return redirect('/wyh0282/login.html')
        else:
            resp = servers_reboot(project_token,serverid)
            if resp.status_code == 202:
                messages.info(request, '重启成功！')
                return redirect('/wyh0282/serverlist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
# 暂停实例
def server_stop(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = servers_pause(project_token,serverid)
        if resp.status_code == 202:
            messages.info(request, '暂停成功！')
            return redirect('/wyh0282/serverlist/')
        else:
            return render(request, 'wyh0282/projectlist.html')
# 取消暂停server
def server_unstop(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = servers_unpause(project_token,serverid)
        if resp.status_code == 202:
            messages.info(request, '取消暂停成功！')
            return redirect('/wyh0282/serverlist/')
        else:
            return render(request, 'wyh0282/projectlist.html')
#  挂起servers
def server_hang(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = servers_suspend(project_token,serverid)
        if resp.status_code == 202:
            messages.info(request, '挂起server成功！')
            return redirect('/wyh0282/serverlist/')
        else:
            return render(request, 'wyh0282/projectlist.html')
#  恢复挂起的servers
def server_rehang(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = servers_resume_suspended(project_token,serverid)
        if resp.status_code == 202:
            messages.info(request, '恢复server成功！')
            return redirect('/wyh0282/serverlist/')
        else:
            return render(request, 'wyh0282/projectlist.html')
#   创建快照
def shot_create(request,serverid):
    if request.method == "POST":
        form = ShotcreatForm(request.POST)
        if form.is_valid():
            shotname = form.cleaned_data.get('shotname')
            project_token = request.session.get("project_token", None)

            res = servers_snapshot(project_token,serverid,shotname)
            if res.status_code == 202:
                messages.info(request, '创建成功！')
                return redirect('/wyh0282/imagelist/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = ShotcreatForm()
    return render(request, 'wyh0282/shotcreate.html', {'form': form})
# 关闭实例
def server_off(request,serverid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = servers_stop(project_token,serverid)
        if resp.status_code == 202:
            messages.info(request, '关闭server成功！')
            return redirect('/wyh0282/serverlist/')
        else:
            return render(request, 'wyh0282/projectlist.html')
# 列举项目映像
def image_lists(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = images_list(project_token)
        if resp.status_code == 200:
            request.session["images_list"] = resp.json()
            return render(request, 'wyh0282/imageslist.html')
        else:
            return redirect('/wyh0282/login/')
# 创建镜像
def image_creates(request):
    if request.method == "POST":
        form = ImagecreatForm(request.POST)
        if form.is_valid():
            imagename = form.cleaned_data.get('imagename')
            project_token = request.session.get("project_token", None)
            container_format = form.cleaned_data.get('container_format')
            disk_format = form.cleaned_data.get('disk_format')
            description = form.cleaned_data.get('description')
            res = image_create(imagename,container_format,disk_format,description,project_token)
            if res.status_code == 201:
                messages.info(request, '创建成功！')
                return redirect('/wyh0282/imagelists/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = ImagecreatForm()
    return render(request, 'wyh0282/imagecreate.html', {'form': form})
# 上传镜像
def image_file(request,imageid):
    if request.method == "POST":
        form = FilecreatForm(request.POST)
        if form.is_valid():
            path = form.cleaned_data.get('path')
            project_token = request.session.get("project_token", None)
            res = image_upload(path,project_token,imageid)
            if res.status_code == 204:
                messages.info(request, '上传成功！')
                return redirect('/wyh0282/imagelists/')
            else:
                return render(request, 'wyh0282/projectlist.html')
    else:
        form = FilecreatForm()
    return render(request, 'wyh0282/filecreate.html', {'form': form})
# 查看镜像详细信息
def image_detail(request,imageid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login')
    user_lists = request.session.get("project_res", None)
    if user_lists:
        return render(request, 'wyh0282/project.html')
    else:
        resp = images_info(imageid,project_token)
        if resp.status_code == 200:
            request.session["image_info"] = resp.json()
            return render(request, 'wyh0282/imageinfo.html')
        else:
            return redirect('/wyh0282/login/')
# 删除映像
def image_delete(request,imageid):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        resp = images_del(imageid,project_token)
        if resp.status_code == 204:
            messages.info(request, '删除成功！')
            return redirect('/wyh0282/imagelists/')
        else:
            return render(request, 'wyh0282/projectlist.html')
def test(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    #print("?????????????")
    if not (domain_token and project_token):
        return redirect('/wyh0282/login.html')
    else:
        return render(request, 'wyh0282/test.html')
